package com.psbc.redis_study.controller;

import com.psbc.redis_study.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/coupon")
public class CouponController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/add")
    private JsonData saveCoupon(@RequestParam(value = "coupon_id",required = true) String couponId){
        //防止其他线程误删掉当前key，将value设置成uuid
        String uuid = UUID.randomUUID().toString();
        String lockKey = "lock:coupon"+couponId;
        lock(couponId,uuid,lockKey);
        return JsonData.buildSuccess();
    }
    public void lock(String couponId,String uuid,String lockKey){
        //lua脚本
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        Boolean booleanLock = redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, 30, TimeUnit.SECONDS);
        System.out.println(uuid+"加锁状态"+booleanLock);
        if (booleanLock){
            try{
                //如果返回值时true，说明获得了锁，可以执行具体的业务逻辑
                //todo
                try {
                    TimeUnit.SECONDS.sleep(10L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                //业务逻辑处理完之后需要解锁，要判断这个value是不是自己的，然后再删除key，要保证判断和删除的
                //原子性，这个可以采用lua脚本来执行
                Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockKey), uuid);
                System.out.println("解锁状态"+result);
            }
        }else {
            //既然没有获得锁，那就先睡眠一段时间，然后自旋继续调用方法获取锁
            try {
                System.out.println("加锁失败，自旋5秒，进入自旋");
                TimeUnit.MILLISECONDS.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock(couponId,uuid,lockKey);
        }
    }
}
